import type { AxiosResponse } from 'axios'
// import { decode } from "iconv-lite";

interface Window {
  showSaveFilePicker: any
}

export const downloadBlobFile = (
  res: AxiosResponse<Blob>,
  fileName: string
) => {
  const blob = res.data
  // console.log(blob);
  const blobUrl = URL.createObjectURL(blob)
  const a = document.createElement('a') // 转换完成，创建一个a标签用于下载
  a.style.display = 'none'
  // 设置href属性为文件路径，download属性可以设置文件名称
  a.href = blobUrl
  a.download = fileName
  document.body.appendChild(a)
  a.click()
  URL.revokeObjectURL(blobUrl)
  a.remove()
}

export const downloadFileWithBlob = async (
  res: AxiosResponse<Blob>,
  name: string,
  type = 'decode'
) => {
  const temp = res.headers['content-disposition']?.split(';')[1].split('=')[1]
  // console.log(temp);
  let fileName = name
  if (temp) {
    // fileName = decode(temp, "utf8");
    // fileName = convertToUTF8(temp);
    fileName = convertToString(temp)
    // console.log(fileName)
    if (fileName.indexOf("utf-8''") > -1) {
      fileName = fileName.replace(`utf-8''`, '')
    }
    if (fileName.indexOf('utf-8') > -1) {
      fileName = fileName.replace(`utf-8`, '')
    }
  }
  // if (type === "decodeUrl") {
  //   fileName = decodeURI(temp.replace("utf-8''", ""));
  // }
  // console.log(fileName);
  // const blob = new Blob([res.data], {
  //   type: "application/excel;charset=utf-8",
  // });
  // if (window.showSaveFilePicker) {
  const downloadType = false
  if (downloadType) {
    const opts = {
      suggestedName: fileName,
      types: [
        {
          description: '导出表格数据',
          accept: { 'application/vnd.ms-excel': ['.xlsx'] },
        },
      ],
    }
    try {
      // @ts-ignore
      const fileHandle = await window.showSaveFilePicker(opts)
      const writableFileStream = await fileHandle.createWritable()
      await writableFileStream.write(res.data)
      await writableFileStream.close()
    } catch (e) {
      if (!String(e).includes('aborted')) {
        downloadBlobFile(res, fileName)
      }
    }
  } else {
    downloadBlobFile(res, fileName)
  }
}

const convertToUTF8 = (content: string) => {
  const surrogate = encodeURIComponent(content)
  let result = ''
  for (let i = 0; i < surrogate.length; ) {
    const character = surrogate[i]
    i += 1
    if (character == '%') {
      const hex = surrogate.substring(i, (i += 2))
      if (hex) {
        result += String.fromCharCode(parseInt(hex, 16))
      }
    } else {
      result += character
    }
  }
  return result
}

const convertToString = (uriStr: string) => {
  return decodeURI(uriStr)
}
